#include				"processor.h"
#include				"handler.h"
#include				"protocol.h"
#include				"MainModule.h"
#include				"AudioModule.h"

Processor::Processor() : _api(0)
{
	_module[MAIN] = new MainModule();
	_module[MAIN]->init();
	_module[AUDIO] = new AudioModule();
	_module[AUDIO]->init();
}

Processor::~Processor()
{

}

void					Processor::setApi(IApi *api)
{
	_api = api;
	for (std::map<ProtocolOperator, AModule*>::iterator it = _module.begin(); it != _module.end(); ++it)
		it->second->setApi(_api);
}

PacketHandler			*Processor::getPacketHandler()
{
	return new PacketHandler(*this);
}

void					Processor::interpret(Packet *packet)
{
	ProtocolOperator	*protocol = packet->getData<ProtocolOperator>(1);
	if (protocol != NULL && _module.find(*protocol) != _module.end())
	{
		(_module[*protocol])->interpret(packet);
	}
	else
		std::cout << "[CRITICAL] Error on calling matching module for protocol = " << (unsigned int) *protocol << std::endl;
	packet->destroy();
	delete protocol;
	delete packet;
}

void					Processor::disconnect(unsigned int id)
{
  _api->network()->closeSocket(id);
  _api->audio()->destroyBuffer(id);
}
